package com.prim.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 两个线程交替打印0-100奇偶数 通过synchronized实现
 */
public class WaitNotifyPrintOddEvenSyn {

    private static int count;

    private static final Object lock = new Object();

    //新建两个线程 两个线程共用同一把锁
    //1个只处理偶数 1个只处理奇数 用位运算
    //用synchronized来通信
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    System.out.println("偶数线程的状态:"+Thread.currentThread().getState());
                    synchronized (lock) {
                        //如果发现是偶数就打印出来
                        if ((count & 1) == 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count);
                            count++;
                        }
                    }
                }
            }
        }, "偶数").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    System.out.println("奇数线程的状态:"+Thread.currentThread().getState());
                    synchronized (lock) {
                        //如果发现是偶数就打印出来
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count);
                            count++;
                        }
                    }
                }
            }
        }, "奇数").start();
    }
}
